<!--
 * @Author: 极客James
 * @Motto: 求知若渴,虚心若愚
 * @Github: https://github.com/Geek-James/ddBuy
 * @掘金: https://juejin.im/user/5c4ebc72e51d4511dc7306ce
 * @LastEditTime: 2019-11-28 22:47:17
 * @Description: 购物车模块
 * @FilePath: /ddBuy/src/views/cart/Cart.vue
 -->
<template>
  <div class="cart">
    <!-- 购物车头部 -->
    <!--头部区域-->
    <header class="
       titleWrapper">
      <h4><strong>{{$t('car.title')}}</strong></h4>
      <div class="clearCart"
           :style="selectedGoodsCount==0?'color:grey':'color:#45c763'"
           @click="clearCart"
           v-show="isShowEmptyCart">{{$t('car.delete')}}</div>
    </header>
    <!-- 购物车没有商品 -->
    <div class="cartWrapper">
      <!-- 购物车为空 -->
      <div class="emptyCart"
           v-show="!isShowEmptyCart">
        <img src="./../../images/cart/empty.png"
             alt="">
        <div class="title">{{$t('car.tip')}}</div>
        <router-link to="/dashboard/home"
                     class="goHome">{{$t('car.walk')}}</router-link>
      </div>
      <!-- 购物车有数据 -->
      <div class="contentWrapper"
           v-show="isShowEmptyCart">
        <div class="contentWrapperList"
             v-for="(goods,index) in xx"
             :key="goods.sid" :index="index">
          <section>
            <div class="shopCartListCon">
              <div class="left">
                <a href="javaScript:;"
                   class="cartCheckBox"
                   :checked="goods.zt"
                   @click.stop="single(goods.sid)"></a>
              </div>
              <div class="center">
                <img :src="goods.img1"  >
              </div>
              <div class="right">
                <a>{{goods.name}}</a>
                 <a>规格：{{goods.sku.sku}}</a>
                <div class="bottomContent">
                  <p class="shopPrice"> {{goods.price | moneyFormat}}</p>
                   <span @click="reduceGoods(goods.sid,goods.sl)">-</span>
                  <div class="shopDeal">
                   
                    <input type="number"
                           disabled
                           v-model="goods.sl">
                    
                  </div>
                  <span @click="addGoods(goods.sid,goods.sl,
       )">+</span>
                </div>
              </div>
            </div>
          </section>
        </div>
        <!-- 提交订单 -->
        <van-submit-bar :price="Zprice"
                        :button-text="submitBarText"
                        @submit="onSubmit"
                        :disabled="!(this.Del.length>0)"
                        v-show="isShowEmptyCart">
          <van-checkbox  v-model="qx"
                        checked-color='#45c763' @click="chechall">{{$t('car.all')}}</van-checkbox>
        </van-submit-bar>
      </div>
      <!-- 猜你喜欢 -->
      <van-divider :style="{ color: 'black', borderColor: 'grey', padding: '0 16px' }">
        {{$t('car.guess')}}
      </van-divider>
      <!-- 商品详情组件 需要注意下底部是否被遮盖 动态设置padding-bottom -->
      <produceItem :product_lists="youLike_product_lists"
                   :style="isShowEmptyCart?'padding-bottom:5.5rem':'padding-bottom:3rem'" />
    </div>
    <Loading :show="isShowLoading" />
    <!-- 回到顶部组件 -->
    <v-top />
  </div>
</template>

<script type="text/javascript">
// 引入组件
import ProduceItem from './../home/components/tabbar/ProduceItem'
import { getGuessYouLike } from './../../serve/api/index.js'
import Loading from '../../components/loading/LoadingGif'
// 引入Vuex
import { mapMutations, mapState, mapGetters } from 'vuex'
import { getLocalStore } from '../../config/global';
// 引入提示框
import { Dialog, Toast } from 'vant';
export default {
  mounted () {
    // 初始化数据
    // this._initData();

    this.show();
  },
  data () {
    return {
      youLike_product_lists: [],
      isShowLoading: false,
      isEmptyCart: false,
      xx:[],
      qx:false,
      Zprice:0,
      Del:[],
      tp:[],
      pd:0,
      sku:[],
    }
  },
  components: {
    ProduceItem,
    Loading
  },
  computed: {
    // 0.结算数量
    submitBarText () {
      const count = this.Del.length;
      return '结算' + count ;
    },
    // 1.是否显示空购物车样式
    isShowEmptyCart () {
      let isshow = false;
      if (true) {
        isshow = true;
      }
      return isshow;
    },
    // 2.延展出store里的shopCart的数据
    ...mapState(['shopCart', 'userInfo']),
    ...mapGetters({
      selectedGoodNum: 'SELECTED_GOODS_COUNT',
      totalPrice: 'SELECTED_GOODS_PRICE'
    }),
    // 3.计算shopCart的数量
    totalCount () {
      return Object.keys(this.shopCart).length;
    },
    // 4.计算shopCart中选中商品的数量
    selectedGoodsCount () {
      let selectedGoodsCount = 0;
      console.log(this.shopCart)
      Object.values(this.shopCart).forEach((goods, index) => {
        if (goods.checked) {
          selectedGoodsCount++;
        }
      });
      return selectedGoodsCount;
    },
    // 5.是否全部选中
    
  //   isCheckedAll: {
  //     get () {
  //       let tag = this.totalCount > 0;
  //       let shopCart = this.xx;
  //       Object.values(shopCart).forEach(goods => {
  //         if (!goods.zt) {
  //           tag = false;
  //         }
  //       });
  //       return tag;
  //     },
  //     set (value) {
  //       // 改变store中的值
  //       // 解决 assigned to but it has no setter.
  //       // https://vuex.vuejs.org/zh/guide/forms.html
  //       //  https://stackoverflow.com/questions/55097118/computed-property-was-assigned-to-but-it-has-no-setter-a-toggle-component
  //       let isCheckedAll = !value;
  //       this.ALL_SELECT_GOODS({ isCheckedAll });
  //     }
  //   }
   },
  methods: {
    // 0.延展mutations中的方法
    ...mapMutations(['ADD_GOODS', 'REDUCE_GOODS', 'SINGLE_SELECT_GOODS', 'ALL_SELECT_GOODS', 'DELETE_SELECT_GOODS', 'ADD_TO_CART']),
    // 1.右上角删除
    clearCart () {
    
      if (this.Del.length > 0) {
        Dialog.confirm({
          title: '温馨提示',
          message: '确定删除选中商品吗?'
        }).then(() => {
            this.Del=[];
          // on confirm 确认删除
         this.xx.map((a)=>{
           if(a.zt==true)
           {
              this.Del.push(a.sid);
           }
          })
           console.log(this.Del)
          this.$axios
          .get("https://localhost:44308/api/app/shop/redisdel?id="+this.Del.join(","))
          .then((a)=>{
            if(a.data>0)
            {
              alert("删除成功");
              this.show();
            }
            else{
              alert("删除失败");
            }
          })
        }).catch(() => {
          // on cancel
        });
      }
    },
    // 2.数据加载
    // async _initData () {
    //   let ref = await getGuessYouLike();
    //   console.log(ref)
    //   if (ref.success) {
    //     this.youLike_product_lists = ref.data.product_list;
    //     this.isShowLoading = false;
    //   }
    // },
  show(){
    this.$axios
    .get("https://localhost:44308/api/app/shop/redis-show")
    .then((a)=>{
      this.xx=a.data;
    
       console.log(a.data)
        for (let index = 0; index < a.data.length; index++) {
        a.data[index].sku=JSON.parse(a.data[index].sku)
         a.data[index].price=a.data[index].sku.price;
         
         console.log(a.data[index].sku)
        }
    
          this.isShowLoading = false;
    })
  
  },
  gai(){
   this.Zprice=0;
    this.xx.map((a)=>{
      if(a.zt==true)
      {
        this.Zprice+=a.sl*a.price*100;
      
      }
    })
  },
  chechall(){    //全选反选
   if(this.qx==false)
   {
     this.xx.map((a)=>{
       a.zt=true;
        if(a.zt==true)
           {
              this.Del.push(a.sid);
           }
     })
   }
   else{
      this.xx.map((a)=>{
       a.zt=false;
       this.Del=[];
     })
   }
   this.gai();
  },
    // 3.减少商品数量
    reduceGoods (goodsID, goodsNum) {
      if (goodsNum > 1) {
        // 3.1 通过goodsID减少商品
        // alert(goodsID)
        // this.REDUCE_GOODS({
        //   goodsID
        // });
        this.xx.map((a)=>{
         if (a.sid==goodsID) {
            a.sl= a.sl-1;
         }
        })
        this.gai();
        

      } else if (goodsNum === 1) {
        Dialog.confirm({
          title: '温馨提示',
          message: '确定删除该商品吗?'
        }).then(() => {
          // on confirm 确认删除
       
          this.$axios
          .get("https://localhost:44308/api/app/shop/redisdel?id="+goodsNum)
          .then((a)=>{
            if(a.data>0)
            {
              alert("删除成功");
              this.show();
            }
            else{
              alert("删除失败");
            }
          })
        }).catch(() => {
          // on cancel
        });
      }
    },
    // 4.增加商品数量 保证传递数据和 mutations 一致
    addGoods (goodsID, goodsName) {
      // this.ADD_GOODS({
      //   goodsID,
      //   goodsName,
      //   goodsSmallImage,
      //   goodsPrice
      // });

        this.xx.map((a)=>{
         if (a.sid==goodsID) {
            a.sl= a.sl+1;
         }
        })
        this.gai();
    },                                  
    // 5.单个商品的选中和非选中
    single (goodsID) {
     this.xx.map((a)=>{
       if(a.sid==goodsID)
       {
         a.zt= !a.zt;
         if(a.zt==true)
         {
           this.Del.push(a.sid);
            console.log(this.Del)
         }
         else
         {
           
           this.Del.forEach ((a)=>{
             
             if(a==goodsID)
             {
               
              console.log(this.pd);
              this.Del.splice(this.pd,1);
              this.pd=0;
              return;
             
             }
           
             this.pd++;
            
           })
        
           console.log(this.Del)
         
         }
       }
       this.gai();
     })
    },
    // 6.去结算
    onSubmit () {
      // 6.1 当选中商品数量大于0跳转
      if (this.Del.length > 0) {
        // // 跳转到订单界面
        // this.$router.push('/order');
   this.xx.map((a)=>{
     if(a.zt==true){
    
       this.tp.push(a)
     }
   })
      localStorage.setItem("ordersj",JSON.stringify( this.tp))
      console.log(this.tp);
       this.$router.push({
        name: "order",
      });



      } else {
        Toast({
          message: '请选择需要结算的商品',
          duration: 1000
        });
      }
    },
  },
}
</script>
<style lang="less" scoped>
.cart {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  .titleWrapper {
    width: 100%;
    height: 2.6rem;
    background: #fff;
    -webkit-background-size: 0.1rem 4.4rem;
    background-size: 0.1rem 4.4rem;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .titleWrapper .clearCart {
    position: absolute;
    right: 0.3rem;
    font-size: 0.8rem;
  }
  .disableClearCart {
    color: grey;
  }
  .cartWrapper {
    width: 100%;
    height: 100rem;
    margin-top: 2.6rem;
    @media screen and (min-width: 300px) and(max-width: 374px) {
      .van-submit-bar {
        bottom: 3.3rem;
      }
    }
    @media screen and (min-width: 375px) and(max-width: 420px) {
      .van-submit-bar {
        bottom: 2.7rem;
      }
    }
    @media screen and (min-width: 420px) and(max-width: 1024px) {
      .van-submit-bar {
        bottom: 1.4rem;
      }
    }
    .emptyCart {
      display: flex;
      flex-direction: column;
      justify-content: center;
      img {
        padding-top: 2rem;
        width: 50%;
        height: 8rem;
        margin: 0 auto;
      }
      .title {
        text-align: center;
        padding: 0.5rem;
      }
      .goHome {
        margin-top: 2rem;
        color: white;
        background-color: #45c763;
        text-align: center;
        margin: 0 auto;
        padding: 0.5rem;
        width: 5rem;
        height: 1rem;
        line-height: 1rem;
        border-radius: 1rem;
      }
    }
    .contentWrapper {
      padding-top: 0.5rem;
      section {
        background-color: #ffffff;
        .shopCartListCon {
          display: flex;
          height: 6rem;
          border-bottom: 0.01rem solid #e0e0e0;
          margin-bottom: 0.7rem;
          padding: 0.5rem 0;
          justify-content: center;
          align-items: center;
          .left {
            flex: 1;
            display: flex;
            a {
              display: inline-block;
              margin-top: 0.8rem;
              margin-left: 0.5rem;
            }
            .cartCheckBox {
              background: url("./../../images/cart/shop-icon.png") no-repeat;
              background-size: 2.5rem 5rem;
              width: 1rem;
              height: 1rem;
            }
            .cartCheckBox[checked] {
              background-position: -1.2rem 0;
            }
          }
          .center {
            flex: 3;
            img {
              width: 100%;
              height: 100%;
            }
          }
          .right {
            flex: 6;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 0.5rem;
            margin-right: 0.5rem;
            position: relative;
            a {
              height: 2.2rem;
              line-height: 1.2rem;
              overflow: hidden;
              margin-bottom: 0.3rem;
              font-size: 0.8rem;
              color: #000;
            }
          }
        }
        .bottomContent {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          .shopPrice {
            font-size: 0.8rem;
          }
          .shopDeal span {
            display: inline-block;
            width: 1rem;
            height: 1.2rem;
            line-height: 1.2rem;
            text-align: center;
          
          }
          .shopDeal input {
            float: left;
            width: 2rem;
            height: 1.2rem;
            text-align: center;
            margin: 0 0.2rem;
            font-size: 0.8rem;
            background-color: #f5f5f5;
            border: 0;
          }
        }
      }
    }
  }
  .van-checkbox {
    margin-left: 0.5rem;
  }
}
</style>
